package cn.tedu._05mvcboot03.controller;

import cn.tedu._05mvcboot03.common.response.JsonResult;
import cn.tedu._05mvcboot03.common.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.ArticleMapper;
import cn.tedu._05mvcboot03.mapper.UserMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserAricleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLogDTO;
import cn.tedu._05mvcboot03.pojo.entity.Article;
import cn.tedu._05mvcboot03.pojo.entity.User;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@Api(tags = "用户模块")
@RestController
@RequestMapping("v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @ApiOperation("登录功能")
    @PostMapping("login")
    public JsonResult userLogin(@RequestBody UserLogDTO userLogDTO,@ApiIgnore HttpSession session){
        log.debug("userLogDTO = " + userLogDTO + ", session = " + session);
        UserVO userVO = userMapper.selectUser(userLogDTO);
        if (userVO == null){ //用户名或密码错误
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
//        登录成功
        session.setAttribute("user",userVO);
        return JsonResult.ok();
    }

    @ApiOperation("发表文章功能")
    @PostMapping("article")
    public JsonResult article(@RequestBody @Validated UserAricleDTO userAricleDTO,
                              @ApiIgnore HttpSession httpSession){

//        1.打印日志
        log.debug("userAricleDTO = " + userAricleDTO + ", httpSession = " + httpSession);

        UserVO user = (UserVO) httpSession.getAttribute("user");
        if (user == null){ //暂时没有用户登录
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Article article = new Article();
        BeanUtils.copyProperties(userAricleDTO,article);
        article.setUserId(user.getId());
        articleMapper.insertArticle(article);
        return JsonResult.ok();
    }

    @ApiOperation("查询指定文章功能")
    @ApiImplicitParam(name = "id",value = "文章ID",required = true,dataType = "int" )
    @GetMapping("selectByArticleId")
    public JsonResult selectByArticledId(@Range(min = 1,max = 100,message = "文章id在1-100之间") @RequestParam int id ){

        return JsonResult.ok(articleMapper.selectByArticleId(id));
    }

}
